package cn.wit.summit.chwan.widgets;

import android.animation.Animator;
import android.animation.AnimatorInflater;
import android.animation.AnimatorListenerAdapter;
import android.animation.AnimatorSet;
import android.animation.ObjectAnimator;
import android.animation.ValueAnimator;
import android.annotation.SuppressLint;
import android.content.Context;
import android.os.Message;
import android.support.annotation.Nullable;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.LinearInterpolator;
import android.view.animation.RotateAnimation;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import java.util.ArrayList;
import java.util.List;

import cn.wit.summit.chwan.R;
import cn.wit.summit.chwan.ui.base.MyApplication;
import cn.wit.summit.chwan.utils.AccountBean;
import cn.wit.summit.chwan.utils.AccountUtil;
import cn.wit.summit.chwan.utils.IntentUtil;
import cn.wit.summit.chwan.utils.PreferenceUtil;
import cn.wit.summit.chwan.utils.StringUtils;

/**
 * Created by Alan on 2018/4/13.
 */

public class RecommendTopEnergyView extends LinearLayout {

    private Context mContext;

    private LinearLayout EnergyRootLl;
    private TextView addEnergyTx;
//    private ImageView addEnergyIv;
    private TextView totalEnergyTx;
    private RelativeLayout addEnergyRl;

    private boolean mIsShowBack = true;
    private AnimatorSet mRightOutSet, mLeftInSet;

    private int totalNum = 0;
    private WaveView waveView;
    private WaveHelper mWaveHelper;

    private boolean isRun = false;
    private final int msgWhat = 1;
    @SuppressLint("HandlerLeak")
    private android.os.Handler handler = new android.os.Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 1:
                    showPositiveSide();
                    break;
                case 2:
                    long time = System.currentTimeMillis();
                    if (time-lastTime>=3) {
                        setWaveStop();
                    }
                    break;
            }
        }
    };

    public RecommendTopEnergyView(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        initView(context, attrs);
    }

    public RecommendTopEnergyView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        initView(context, attrs);
    }

    private void initView(Context context, AttributeSet attrs) {
        this.mContext = context;

        View rootView = LayoutInflater.from(context).inflate(R.layout.part_top_energy_view, null);
        EnergyRootLl = rootView.findViewById(R.id.EnergyRootLl);
//        addEnergyIv = rootView.findViewById(R.id.addEnergyIv);
        addEnergyTx = rootView.findViewById(R.id.addEnergyTx);
        totalEnergyTx = rootView.findViewById(R.id.totalEnergyTx);
        addEnergyRl = rootView.findViewById(R.id.addEnergyRl);
        waveView = rootView.findViewById(R.id.addEnergyWave);
        waveView.setShowWave(true);
        waveView.setWaterLevelRatio(0.5f);
        mWaveHelper = new WaveHelper(waveView);
        this.removeAllViews();
        this.addView(rootView);

        EnergyRootLl.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                if (AccountUtil.getInstance().getAccountData()==null) {//未登陆
                    initNum(0);
                    IntentUtil.getInstance().goLoginActivity(mContext);
                    return;
                }

                String url = MyApplication.cfgPlug.getValue_energy_secret_url();
                IntentUtil.getInstance().goShareWebActivity(mContext, url);
            }
        });

        setAnimators();
        setCameraDistance();
        setWaveStart();
    }

    // 设置动画
    private void setAnimators() {
        mRightOutSet = (AnimatorSet) AnimatorInflater.loadAnimator(mContext, R.animator.energy_rightout);
        mLeftInSet = (AnimatorSet) AnimatorInflater.loadAnimator(mContext, R.animator.energy_leftin);

        // 设置点击事件
        mRightOutSet.addListener(new AnimatorListenerAdapter() {
            @Override
            public void onAnimationStart(Animator animation) {
                super.onAnimationStart(animation);
                isRun = true;
            }
        });
        mLeftInSet.addListener(new AnimatorListenerAdapter() {
            @Override
            public void onAnimationEnd(Animator animation) {
                super.onAnimationEnd(animation);
                if (!mIsShowBack) {
                    handler.removeMessages(msgWhat);
                    Message message = new Message();
                    message.what = msgWhat;
                    handler.sendMessageDelayed(message, 1000);
                } else {
                    isRun = false;
                }
            }
        });
    }

    // 改变视角距离, 贴近屏幕
    private void setCameraDistance() {
        int distance = 16000;
        float scale = getResources().getDisplayMetrics().density * distance;
        addEnergyTx.setCameraDistance(scale);
        addEnergyRl.setCameraDistance(scale);
//        addEnergyIv.setCameraDistance(scale);

        showPositiveSide();
        mRightOutSet.end();
        mLeftInSet.end();

        AccountBean accountBean = AccountUtil.getInstance().getAccountData();
        if (accountBean==null) {//未登陆
            String gameid=   PreferenceUtil.getPreferences(getContext(), "toursEnergyPreGameID");
            if (StringUtils.isEmpty(gameid)){
                totalEnergyTx.setText("0");
            }else {
                totalEnergyTx.setText("10");
            }
        } else {
            totalEnergyTx.setText(accountBean.getEnergies()+"");
        }
    }

    public void initNum(int total){
        initNum(0, total);
    }

    private void initNum(int add, int total){
        if (AccountUtil.getInstance().getAccountData()==null) {//未登陆
         String gameid=   PreferenceUtil.getPreferences(getContext(), "toursEnergyPreGameID");
         if (StringUtils.isEmpty(gameid)){
            totalEnergyTx.setText("0");
         }else {
            totalEnergyTx.setText("10");
         }
            showPositiveSide();
            mRightOutSet.end();
            mLeftInSet.end();
        } else {
            addEnergyTx.setText("+"+add);
            totalEnergyTx.setText(total+"");
        }
        invalidate();
    }

    public void addEnergyNum(final int num) {
//        if (AccountUtil.getInstance().getAccountData()==null) {//未登陆
//            totalEnergyTx.setText("0");
//            return;
//        }
        showTotalResult(num);

        if (isRun || num==0) {
            return;
        }

        if (!mIsShowBack) {
            showPositiveSide();
        } else {
            showNegativeSide();
        }
    }

    // 正面朝上
    private void showPositiveSide() {
        mRightOutSet.setTarget(addEnergyTx);
        mLeftInSet.setTarget(addEnergyRl);
//        mLeftInSet.setTarget(addEnergyIv);
        mRightOutSet.start();
        mLeftInSet.start();
        mIsShowBack = true;
    }

    // 背面朝上
    private void showNegativeSide() {
//        mRightOutSet.setTarget(addEnergyIv);
        mRightOutSet.setTarget(addEnergyRl);
        mLeftInSet.setTarget(addEnergyTx);
        mRightOutSet.start();
        mLeftInSet.start();
        mIsShowBack = false;
    }

    private void showTotalResult(int num) {
        addEnergyTx.setText("+"+num);

        String str = totalEnergyTx.getText().toString();
        int m = 0;
        if (StringUtils.isEmpty(str))
            m = 0;
        else
            m = Integer.valueOf(str);
        if (AccountUtil.getInstance().getAccountData()==null){
            if (m==0)m=num;
            totalNum = m;
        }else {
            totalNum = m + num;

        }
        totalEnergyTx.setText(totalNum+"");
        invalidate();
    }

    //是否在动
    public boolean isWaveStart() {
        return mWaveHelper.isRun();
    }

    //动起来
    public void setWaveStart() {
        mWaveHelper.start();
    }

    //停下来
    public void setWaveStop() {
        mWaveHelper.cancel();
    }

    //设置水位高度（0.0f ~ 1.0f）
    public void setWaveLevel(float waterLevelRatio) {
        waveView.setWaterLevelRatio(waterLevelRatio);
    }

    public class WaveHelper {
        private WaveView mWaveView;

        private AnimatorSet mAnimatorSet;

        public WaveHelper(WaveView waveView) {
            mWaveView = waveView;
            initAnimation();
        }

        public boolean isRun() {
            return mAnimatorSet.isRunning();
        }

        public void start() {
            mWaveView.setShowWave(true);
            if (mAnimatorSet != null) {
                mAnimatorSet.start();
            }
        }

        private void initAnimation() {
            List<Animator> animators = new ArrayList<>();

            // horizontal animation.
            // wave waves infinitely.
            ObjectAnimator waveShiftAnim = ObjectAnimator.ofFloat(
                    mWaveView, "waveShiftRatio", 0f, 1f);
            waveShiftAnim.setRepeatCount(ValueAnimator.INFINITE);
            waveShiftAnim.setDuration(2000);
            waveShiftAnim.setInterpolator(new LinearInterpolator());
            animators.add(waveShiftAnim);

            // vertical animation.
            // water level increases from 0 to center of WaveView
//            ObjectAnimator waterLevelAnim = ObjectAnimator.ofFloat(
//                    mWaveView, "waterLevelRatio", 0.3f, 0.3f);
//            waterLevelAnim.setDuration(10000);
//            waterLevelAnim.setInterpolator(new DecelerateInterpolator());
//            animators.add(waterLevelAnim);

            // amplitude animation.
            // wave grows big then grows small, repeatedly
            ObjectAnimator amplitudeAnim = ObjectAnimator.ofFloat(
                    mWaveView, "amplitudeRatio", 0.05f, 0.05f);
            amplitudeAnim.setRepeatCount(ValueAnimator.INFINITE);
            amplitudeAnim.setRepeatMode(ValueAnimator.REVERSE);
            amplitudeAnim.setDuration(5000);
            amplitudeAnim.setInterpolator(new LinearInterpolator());
            animators.add(amplitudeAnim);

            mAnimatorSet = new AnimatorSet();
            mAnimatorSet.playTogether(animators);
        }

        public void cancel() {
            if (mAnimatorSet != null) {
                mAnimatorSet.end();
            }
        }
    }

    private float mDegress;
    private long lastTime = 0l;
    public void changeRotate(float degree) {
//        if (degree>=27.5f)
//            degree = 27.5f;
//        else if (degree<=-27.5f)
//            degree = -27.5f;
        RotateAnimation rotateAnimation = new RotateAnimation(mDegress, degree
                , Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f);
        rotateAnimation.setDuration(50);
        rotateAnimation.setFillAfter(true);
        lastTime = System.currentTimeMillis();
        waveView.startAnimation(rotateAnimation);
        mDegress = degree;
//        setWaveStart();
//        handler.removeMessages(2);
//        Message msg = new Message();
//        msg.what = 2;
//        handler.sendMessageDelayed(msg, 3000);
    }
}
